package handlers

import (
	"notabug.org/alimiracle/my-website-api/hash"
	"notabug.org/alimiracle/my-website-api/jwt_helpers"
	"notabug.org/alimiracle/my-website-api/models"

	"github.com/gofiber/fiber/v2"
)

func (self Handler) Login(c *fiber.Ctx) error {
	body := models.User{}
	if err := c.BodyParser(&body); err != nil {
		c.Status(fiber.StatusBadRequest)
		return c.JSON(fiber.Map{
			"error": err.Error(),
		})
	}
	var user models.User
	self.Database.FindUser(body.Name, &user)
	if user.ID == 0 {
		c.Status(fiber.StatusNotFound)
		return c.JSON(fiber.Map{
			"error": "User not found",
		})
	}

	test_password := hash.CheckPasswordHash(body.Pass, user.Pass)

	if test_password != true {
		c.Status(fiber.StatusBadRequest)
		return c.JSON(fiber.Map{
			"error": "Invalid password",
		})
	}

	t, err := jwt_helpers.Create_token(user)

	if err != nil {
		return c.SendStatus(fiber.StatusInternalServerError)
	}

	return c.JSON(fiber.Map{"token": t})
}
